import { useCrudForm } from "@/composables/useCrudForm";
import { probationFormConfig } from "../form-config";
import { formatDateTime } from "@/utils/xenUtils";
import SysHrProbationRequestBillApi from "../api/index";
import commonApi from "@/api/common";
import type {
  ISysHrProbationRequestBill,
  ISysHrProbationRequestBillVm,
} from "../api/interface";

/**
 * 转正申请单信息专用 Composable
 */
export function useProbationInfo() {
  // 创建API实例
  const api = SysHrProbationRequestBillApi();

  // API配置
  const apiConfig = {
    search: api.search,
    get: api.get,
    add: api.add,
    edit: api.edit,
    delete: api.delete,
    // 单据编号接口 - 适配器处理类型差异
    getBillCode: async () => {
      const result = await api.getBillCode();
      return { Data: result.Data || "" };
    },
  };

  // 选项数据加载器
  const optionLoaders = {
    orgId: async () => {
      const commonApiInstance = commonApi();
      const result = await commonApiInstance.GetParentsTree();
      // 转换为useCrudForm期望的格式
      return result.map((item: any) => ({
        Value: item.Value,
        Text: item.Text,
      }));
    },
    companyId: async () => {
      const commonApiInstance = commonApi();
      const result = await commonApiInstance.GetUserCompanies();
      // 转换为useCrudForm期望的格式
      return result.map((item: any) => ({
        Value: item.Value,
        Text: item.Text,
      }));
    },
  };

  // 使用通用CRUD表单
  const crudForm = useCrudForm<ISysHrProbationRequestBill, ISysHrProbationRequestBillVm>(
    probationFormConfig,
    apiConfig,
    optionLoaders
  );

  /**
   * 转换表单数据为API格式（新增）
   */
  const convertFormDataToApiFormatForCreate = (): ISysHrProbationRequestBillVm => {
    return {
      Entity: {
        // 基本信息字段 - 新增时不传ID，由后端自动生成
        EntryDate: crudForm.formData.entryDate ? new Date(crudForm.formData.entryDate) : null,
        RegDate: crudForm.formData.regDate ? new Date(crudForm.formData.regDate) : null,
        ProbationStartDate: crudForm.formData.probationStartDate ? new Date(crudForm.formData.probationStartDate) : null,
        ProbationEndDate: crudForm.formData.probationEndDate ? new Date(crudForm.formData.probationEndDate) : null,
        ProbationSalary: crudForm.formData.probationSalary || null,
        RegularSalary: crudForm.formData.regularSalary || null,
        JobContent: crudForm.formData.jobContent || null,
        JobAchievements: crudForm.formData.jobAchievements || null,
        Remarks: crudForm.formData.remarks || null,
        RegOpinion: crudForm.formData.regOpinion || null,
        Status: null,
        RecruitNo: null,
        ArrivalDate: null,
        CurrentSalary: null,
        ExpectedSalary: null,
        WorkExperience: null,
        InitialTestTime: null,
        InitialResult: null,
        InitialComment: null,
        ReExamTime: null,
        ReExamResult: null,
        ReExamComment: null,
        FinalResult: null,
        FinalRemark: null,
        RejectReason: null,
        BillCode: crudForm.formData.billCode || null,
        BillStatus: null,
        WorkflowStatus: null,
        Remark: crudForm.formData.remark || null,
        Approver: null,
        ApprovalTime: null,
        Name: crudForm.formData.name || null,
        StaffNo: crudForm.formData.staffNo || null,
        BirthDate: crudForm.formData.birthDate ? new Date(crudForm.formData.birthDate) : null,
        Age: null,
        Gender: crudForm.formData.gender || null,
        Ethnicity: null,
        HighestEducation: null,
        MaritalStatus: null,
        PhotoId: null,
        Photo: undefined,
        IdCardNo: crudForm.formData.idCardNo || null,
        IdCardFrontPhotoId: null,
        IdCardFrontPhoto: undefined,
        IdCardBackPhotoId: null,
        IdCardBackPhoto: undefined,
        HouseholdRegistration: null,
        NativePlace: null,
        PoliticalStatus: null,
        PartyJoinDate: null,
        PartyBranch: null,
        ArchiveLocation: null,
        ArchiveNo: null,
        ArchiveTransferOutDate: null,
        ArchiveTransferInDate: null,
        HomeAddress: null,
        Phone: crudForm.formData.phone || null,
        Email: crudForm.formData.email || null,
        SalaryBank: null,
        SalaryAccount: null,
        BonusBank: null,
        BonusAccount: null,
        OrgId: crudForm.pickerValues.companyId || crudForm.formData.companyId || null,
        Org: undefined,
        GroupId: crudForm.pickerValues.orgId || crudForm.formData.orgId || null,
        Group: undefined,
        JobPositionId: null,
        JobPosition: undefined,
        ResumeId: null,
        Resume: undefined,
        HireDate: null,
        ConfirmationDate: null,
        EmploymentType: null,
        ContractType: null,
        ContractNo: null,
        ContractStartDate: null,
        ContractEndDate: null,
        ResignationDate: null,
        ResignationReason: null,
        ResignationType: null,
        State: null,
        BloodType: null,
        Hobbies: null,
      },
      ActionName: null,
      IsMyApprove: null,
      Remark: null,
    };
  };

  /**
   * 转换表单数据为API格式（编辑）
   */
  const convertFormDataToApiFormatForEdit = (): ISysHrProbationRequestBillVm => {
    const originalData = crudForm.originalData.value;
    if (!originalData) {
      throw new Error("原始数据不存在");
    }

    return {
      Entity: {
        // 基本字段
        ID: originalData.ID || null,
        EntryDate: crudForm.formData.entryDate ? new Date(crudForm.formData.entryDate) : originalData.EntryDate,
        RegDate: crudForm.formData.regDate ? new Date(crudForm.formData.regDate) : originalData.RegDate,
        ProbationStartDate: crudForm.formData.probationStartDate ? new Date(crudForm.formData.probationStartDate) : originalData.ProbationStartDate,
        ProbationEndDate: crudForm.formData.probationEndDate ? new Date(crudForm.formData.probationEndDate) : originalData.ProbationEndDate,
        ProbationSalary: crudForm.formData.probationSalary || originalData.ProbationSalary,
        RegularSalary: crudForm.formData.regularSalary || originalData.RegularSalary,
        JobContent: crudForm.formData.jobContent || originalData.JobContent,
        JobAchievements: crudForm.formData.jobAchievements || originalData.JobAchievements,
        Remarks: crudForm.formData.remarks || originalData.Remarks,
        RegOpinion: crudForm.formData.regOpinion || originalData.RegOpinion,
        Status: originalData.Status,
        RecruitNo: originalData.RecruitNo,
        ArrivalDate: originalData.ArrivalDate,
        CurrentSalary: originalData.CurrentSalary,
        ExpectedSalary: originalData.ExpectedSalary,
        WorkExperience: originalData.WorkExperience,
        InitialTestTime: originalData.InitialTestTime,
        InitialResult: originalData.InitialResult,
        InitialComment: originalData.InitialComment,
        ReExamTime: originalData.ReExamTime,
        ReExamResult: originalData.ReExamResult,
        ReExamComment: originalData.ReExamComment,
        FinalResult: originalData.FinalResult,
        FinalRemark: originalData.FinalRemark,
        RejectReason: originalData.RejectReason,
        BillCode: crudForm.formData.billCode || originalData.BillCode,
        BillStatus: '草稿',
        WorkflowStatus: '提交中',
        Remark: crudForm.formData.remark || originalData.Remark,
        Approver: originalData.Approver,
        ApprovalTime: originalData.ApprovalTime,
        Name: crudForm.formData.name || originalData.Name,
        StaffNo: crudForm.formData.staffNo || originalData.StaffNo,
        BirthDate: crudForm.formData.birthDate ? new Date(crudForm.formData.birthDate) : originalData.BirthDate,
        Age: originalData.Age,
        Gender: crudForm.formData.gender || originalData.Gender,
        Ethnicity: originalData.Ethnicity,
        HighestEducation: originalData.HighestEducation,
        MaritalStatus: originalData.MaritalStatus,
        PhotoId: originalData.PhotoId,
        Photo: originalData.Photo,
        IdCardNo: crudForm.formData.idCardNo || originalData.IdCardNo,
        IdCardFrontPhotoId: originalData.IdCardFrontPhotoId,
        IdCardFrontPhoto: originalData.IdCardFrontPhoto,
        IdCardBackPhotoId: originalData.IdCardBackPhotoId,
        IdCardBackPhoto: originalData.IdCardBackPhoto,
        HouseholdRegistration: originalData.HouseholdRegistration,
        NativePlace: originalData.NativePlace,
        PoliticalStatus: originalData.PoliticalStatus,
        PartyJoinDate: originalData.PartyJoinDate,
        PartyBranch: originalData.PartyBranch,
        ArchiveLocation: originalData.ArchiveLocation,
        ArchiveNo: originalData.ArchiveNo,
        ArchiveTransferOutDate: originalData.ArchiveTransferOutDate,
        ArchiveTransferInDate: originalData.ArchiveTransferInDate,
        HomeAddress: originalData.HomeAddress,
        Phone: crudForm.formData.phone || originalData.Phone,
        Email: crudForm.formData.email || originalData.Email,
        SalaryBank: originalData.SalaryBank,
        SalaryAccount: originalData.SalaryAccount,
        BonusBank: originalData.BonusBank,
        BonusAccount: originalData.BonusAccount,
        OrgId: crudForm.pickerValues.companyId || crudForm.formData.companyId || originalData.OrgId,
        Org: originalData.Org,
        GroupId: crudForm.pickerValues.orgId || crudForm.formData.orgId || originalData.GroupId,
        Group: originalData.Group,
        JobPositionId: originalData.JobPositionId,
        JobPosition: originalData.JobPosition,
        ResumeId: originalData.ResumeId,
        Resume: originalData.Resume,
        HireDate: originalData.HireDate,
        ConfirmationDate: originalData.ConfirmationDate,
        EmploymentType: originalData.EmploymentType,
        ContractType: originalData.ContractType,
        ContractNo: originalData.ContractNo,
        ContractStartDate: originalData.ContractStartDate,
        ContractEndDate: originalData.ContractEndDate,
        ResignationDate: originalData.ResignationDate,
        ResignationReason: originalData.ResignationReason,
        ResignationType: originalData.ResignationType,
        State: originalData.State,
        BloodType: originalData.BloodType,
        Hobbies: originalData.Hobbies,
      },
      ActionName: null,
      IsMyApprove: null,
      Remark: null,
    };
  };

  /**
   * 字段映射配置（API字段路径到表单字段的映射）
   */
  const fieldMapping = {
    // 单据信息
    billCode: "BillCode",
    billStatus: "BillStatus",
    workflowStatus: "WorkflowStatus",
    remark: "Remark",

    // 员工基本信息
    name: "Name",
    staffNo: "StaffNo",
    regularStaffNo: "RegularStaffNo",
    gender: "Gender",
    phone: "Phone",
    idCardNo: "IdCardNo",
    birthDate: "BirthDate",
    companyId: "Org.Name",
    orgId: "GroupId",
    org: "Group.GroupName",
    email: "Email",

    // 转正基本信息
    entryDate: "EntryDate",
    regDate: "RegDate",

    // 试用期信息
    probationStartDate: "ProbationStartDate",
    probationEndDate: "ProbationEndDate",
    probationSalary: "ProbationSalary",

    // 转正薪资信息
    regularSalary: "RegularSalary",

    // 转正评估内容
    jobContent: "JobContent",
    jobAchievements: "JobAchievements",
    regOpinion: "RegOpinion",
    remarks: "Remarks",

    // 流程信息
    approver: "Approver",
    approvalTime: "ApprovalTime",
  };

  /**
   * 加载转正申请单详情数据
   */
  const loadProbationDetail = async (id: string): Promise<{ success: boolean; isMyApprove?: boolean }> => {
    // 直接调用API获取完整响应
    const response = await api.get(id);

    if (response && response.Entity) {
      const detail = response.Entity;

      // 设置原始数据
      crudForm.originalData.value = detail;

      // 检查原始数据中的日期字段
      const dateFields = ["ApprovalTime", "EntryDate", "RegDate", "ProbationStartDate", "ProbationEndDate", "BirthDate"];
      dateFields.forEach(field => {
        if ((detail as any)[field]) {
          console.log(`原始数据中的日期字段 ${field}:`, (detail as any)[field]);
        }
      });

      // 先使用通用转换
      crudForm.convertApiDataToFormData(detail, fieldMapping);

      // 添加特殊处理，确保选择器字段正确映射
      await ensurePickerFieldsMapping(detail);

      return {
        success: true,
        isMyApprove: response.IsMyApprove || false
      };
    }
    return { success: false };
  };

  /**
   * 确保选择器字段正确映射
   */
  const ensurePickerFieldsMapping = async (apiData: any) => {
    // 处理单据编号
    if (apiData.BillCode) {
      crudForm.formData.billCode = apiData.BillCode;
    }

    // 处理单据状态
    if (apiData.BillStatus !== undefined) {
      const statusText = apiData.BillStatus === "草稿" ? "草稿" : "正文";
      crudForm.formData.billStatus = statusText;
      crudForm.pickerValues.billStatus = apiData.BillStatus.toString();
    }

    // 处理工作流状态显示
    if (apiData.WorkflowStatus !== undefined) {
      crudForm.formData.workflowStatus = apiData.WorkflowStatus || "";
    }

    // 处理性别（如果是文字则直接使用，如果是数字则转换）
    if (apiData.Gender !== undefined) {
      if (typeof apiData.Gender === 'string') {
        // 接口返回文字，直接使用
        crudForm.formData.gender = apiData.Gender;
        // 为picker设置对应的值
        const genderOptions = [
          { value: "1", text: "男" },
          { value: "2", text: "女" },
          { value: "0", text: "未知" }
        ];
        const genderOption = genderOptions.find(item => item.text === apiData.Gender);
        if (genderOption) {
          crudForm.pickerValues.gender = genderOption.value;
        }
      } else {
        // 数字ID转换为文字
        const genderOptions = [
          { value: "1", text: "男" },
          { value: "2", text: "女" },
          { value: "0", text: "未知" }
        ];
        const genderOption = genderOptions.find(item => item.value === apiData.Gender?.toString());
        if (genderOption) {
          crudForm.formData.gender = genderOption.text;
          crudForm.pickerValues.gender = genderOption.value;
        }
      }
    }

    // 处理所属公司（只读字段显示公司名称）
    if (apiData.OrgId) {
      const companyOptions = probationFormConfig.companyId?.optionsData || [];
      const companyOption = companyOptions.find((item: any) => item.value === apiData.OrgId);
      if (companyOption) {
        // 只读字段显示公司名称
        crudForm.formData.companyId = companyOption.text;
        crudForm.pickerValues.companyId = companyOption.value;
      } else {
        // 如果找不到匹配的公司，尝试从Org对象获取公司名称
        if (apiData.Org && apiData.Org.Name) {
          crudForm.formData.companyId = apiData.Org.Name;
        } else if (apiData.Org && apiData.Org.OrgName) {
          crudForm.formData.companyId = apiData.Org.OrgName;
        } else {
          crudForm.formData.companyId = apiData.OrgId;
        }
        crudForm.pickerValues.companyId = apiData.OrgId;
      }
    }

    // 处理所属部门
    if (apiData.GroupId) {
      // 对于department-picker类型，formData和pickerValues都存储ID
      crudForm.formData.orgId = apiData.GroupId;
      crudForm.pickerValues.orgId = apiData.GroupId;

      console.log('详情页部门信息:', {
        GroupId: apiData.GroupId,
        formDataOrgId: crudForm.formData.orgId,
        pickerValuesOrgId: crudForm.pickerValues.orgId
      });
    }

    // 处理基本信息字段
    if (apiData.Name) {
      crudForm.formData.name = apiData.Name;
    }
    if (apiData.StaffNo) {
      crudForm.formData.staffNo = apiData.StaffNo;
    }
    if (apiData.Phone) {
      crudForm.formData.phone = apiData.Phone;
    }
    if (apiData.IdCardNo) {
      crudForm.formData.idCardNo = apiData.IdCardNo;
    }
    if (apiData.Email) {
      crudForm.formData.email = apiData.Email;
    }

    // 处理薪资字段
    if (apiData.ProbationSalary) {
      crudForm.formData.probationSalary = apiData.ProbationSalary;
    }
    if (apiData.RegularSalary) {
      crudForm.formData.regularSalary = apiData.RegularSalary;
    }

    // 处理转正评估内容
    if (apiData.JobContent) {
      crudForm.formData.jobContent = apiData.JobContent;
    }
    if (apiData.JobAchievements) {
      crudForm.formData.jobAchievements = apiData.JobAchievements;
    }
    if (apiData.RegOpinion) {
      crudForm.formData.regOpinion = apiData.RegOpinion;
    }
    if (apiData.Remarks) {
      crudForm.formData.remarks = apiData.Remarks;
    }

    // 处理日期字段格式化
    const dateFields = [
      { api: "BirthDate", form: "birthDate" },
      { api: "EntryDate", form: "entryDate" },
      { api: "RegDate", form: "regDate" },
      { api: "ProbationStartDate", form: "probationStartDate" },
      { api: "ProbationEndDate", form: "probationEndDate" }
    ];

    dateFields.forEach(({ api, form }) => {
      if (apiData[api]) {
        const formattedDateTime = formatDateTime(apiData[api]);
        crudForm.formData[form] = formattedDateTime ? formattedDateTime.split(' ')[0] : '';
      }
    });

    // 处理审批时间格式化
    if (apiData.ApprovalTime) {
      crudForm.formData.approvalTime = formatDateTime(apiData.ApprovalTime);
    }

    // 处理审批人
    if (apiData.Approver) {
      crudForm.formData.approver = apiData.Approver;
    }
  };

  /**
   * 创建转正申请单（两步提交流程）
   * 第一步：调用Add接口保存草稿
   * 第二步：调用Edit接口提交
   */
  const createProbation = async (): Promise<{
    success: boolean;
    data?: ISysHrProbationRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    // 第一步：调用Add接口保存草稿
    const apiData = convertFormDataToApiFormatForCreate();
    const addResult = await crudForm.create(apiData);


    // 第二步：调用Edit接口进行提交
    // 设置原始数据为第一步返回的结果，用于Edit接口
    crudForm.originalData.value = addResult;

    // 创建编辑数据格式进行提交
    const editApiData = convertFormDataToApiFormatForEdit();

    const editResult = await crudForm.update(editApiData);

    if (!editResult) {
      return {
        success: false,
        validation: validationResult,
        error: "提交失败，数据已保存为草稿，请稍后重试"
      };
    }

    return {
      success: true,
      data: editResult,
      validation: validationResult
    };
  };

  /**
   * 保存转正申请单（编辑）
   */
  const saveProbation = async (): Promise<{
    success: boolean;
    data?: ISysHrProbationRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    // 验证关键数据
    if (!crudForm.originalData.value) {
      return {
        success: false,
        error: "原始数据丢失，请重新加载页面",
        validation: validationResult
      };
    }

    const apiData = convertFormDataToApiFormatForEdit();
    const result = await crudForm.update(apiData);

    return {
      success: result !== null,
      data: result || undefined,
      validation: validationResult
    };
  };

  /**
   * 更新表单配置中的部门和公司数据
   */
  const updateDepartmentData = async () => {
    const commonApiInstance = commonApi();

    // 加载部门数据
    const departmentData = await commonApiInstance.GetParentsTree();
    if (probationFormConfig.orgId && departmentData) {
      probationFormConfig.orgId.departmentData = departmentData;
      // 同时设置optionsData，用于数据映射
      probationFormConfig.orgId.optionsData = departmentData.map((item: any) => ({
        value: item.Value,
        text: item.Text,
      }));
    }

    // 加载公司数据
    const companyData = await commonApiInstance.GetUserCompanies();
    if (probationFormConfig.companyId && companyData) {
      probationFormConfig.companyId.optionsData = companyData.map((item: any) => ({
        value: item.Value,
        text: item.Text,
      }));
    }

    return { departmentData, companyData };
  };

  /**
   * 获取人员信息并初始化表单字段
   */
  const initializePersonInfo = async (): Promise<boolean> => {
    // 获取人员信息
    const personInfoResponse = await api.getPersonInfo();
    if (personInfoResponse && personInfoResponse.Data) {
      const personInfo = personInfoResponse.Data;

      // 初始化基本字段
      if (personInfo.Name) {
        crudForm.formData.name = personInfo.Name;
      }
      if (personInfo.StaffNo) {
        crudForm.formData.staffNo = personInfo.StaffNo;
      }
      if (personInfo.Phone) {
        crudForm.formData.phone = personInfo.Phone;
      }
      if (personInfo.IdCardNo) {
        crudForm.formData.idCardNo = personInfo.IdCardNo;
      }
      if (personInfo.Email) {
        crudForm.formData.email = personInfo.Email;
      }

      // 处理性别（接口直接返回文字）
      if (personInfo.Gender) {
        crudForm.formData.gender = personInfo.Gender;
        // 需要为picker设置对应的值
        const genderOptions = [
          { value: "1", text: "男" },
          { value: "2", text: "女" },
          { value: "0", text: "未知" }
        ];
        const genderOption = genderOptions.find(item => item.text === personInfo.Gender);
        if (genderOption) {
          crudForm.pickerValues.gender = genderOption.value;
        }
      }

      // 处理出生日期
      if (personInfo.BirthDate) {
        const formattedDateTime = formatDateTime(personInfo.BirthDate);
        crudForm.formData.birthDate = formattedDateTime ? formattedDateTime.split(' ')[0] : '';
      }

      // 处理入职时间
      if (personInfo.HireDate) {
        const formattedDateTime = formatDateTime(personInfo.HireDate);
        crudForm.formData.entryDate = formattedDateTime ? formattedDateTime.split(' ')[0] : '';
      }

      // 处理公司信息（只读字段显示公司名称）
      if (personInfo.OrgId) {
        const companyOptions = probationFormConfig.companyId?.optionsData || [];
        const companyOption = companyOptions.find((item: any) => item.value === personInfo.OrgId);
        if (companyOption) {
          // 只读字段显示公司名称
          crudForm.formData.companyId = companyOption.text;
          crudForm.pickerValues.companyId = companyOption.value;
          console.log('初始化公司信息:', {
            OrgId: personInfo.OrgId,
            companyText: companyOption.text,
            companyValue: companyOption.value
          });
        } else {
          // 如果找不到匹配的公司，尝试通过接口获取公司名称或使用ID
          if (personInfo.OrgName) {
            crudForm.formData.companyId = personInfo.OrgName;
          } else {
            crudForm.formData.companyId = personInfo.OrgId;
          }
          crudForm.pickerValues.companyId = personInfo.OrgId;
          console.log('未找到匹配的公司选项，使用名称或ID:', personInfo.OrgName || personInfo.OrgId);
        }
      }

      // 处理部门ID（department-picker需要ID进行回显）
      if (personInfo.GroupId) {
        // 对于department-picker类型，formData和pickerValues都存储ID
        crudForm.formData.orgId = personInfo.GroupId;
        crudForm.pickerValues.orgId = personInfo.GroupId;

        console.log('初始化部门信息:', {
          GroupId: personInfo.GroupId,
          formDataOrgId: crudForm.formData.orgId,
          pickerValuesOrgId: crudForm.pickerValues.orgId
        });
      }

      return true;
    }
    return false;
  };

  /**
   * 重写 initializeOptions 方法，同时更新部门和公司数据
   */
  const initializeOptions = async (): Promise<boolean> => {
    // 先调用原始的 initializeOptions
    const result = await crudForm.initializeOptions();

    // 然后更新部门和公司数据
    await updateDepartmentData();

    return result;
  };

  return {
    // 继承通用CRUD表单的所有功能
    ...crudForm,

    // 重写 initializeOptions 方法
    initializeOptions,

    // 转正申请单信息专用方法
    loadProbationDetail,
    createProbation,
    saveProbation,
    updateDepartmentData,
    initializePersonInfo,

    // API数据转换方法
    convertFormDataToApiFormatForCreate,
    convertFormDataToApiFormatForEdit,

    // 字段映射
    fieldMapping,
  };
}
